﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Marmat.Forms
{
    /// <summary>
    /// 虚拟滚动控件。
    /// </summary>
    public class VirtualScrollableControl : System.Windows.Forms.Control
    {
        /// <summary>
        /// 构建 VirtualScrollableControl 实例
        /// </summary>
        public VirtualScrollableControl()
        {
            SetStyle(ControlStyles.ResizeRedraw, true); //尺寸变化后绘制
            SetStyle(ControlStyles.Opaque, false); //改善绘图质量
            SetStyle(ControlStyles.SupportsTransparentBackColor, true); //使控件支持透明色
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            this.ScrollableControl = new VirtualScrollableControlExtension(this);
            this.ScrollableControl.Scroll += this.ScrollableControl_Scroll;
        }

        private void ScrollableControl_Scroll(object sender, ScrollEventArgs e)
        {
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            this.ScrollableControl.OnPaint(e);
        }

        /// <summary>
        /// 滚动条的扩展对象
        /// </summary>
        protected VirtualScrollableControlExtension ScrollableControl { get; }

        /// <summary>
        /// 处理 windows 消息。
        /// </summary>
        /// <param name="m"></param>
        protected override void WndProc(ref Message m)
        {
            if (this.ScrollableControl.BeforeWndProc(ref m, out var arguments))
                base.WndProc(ref m);
            this.ScrollableControl.AfterWndProc(m, arguments);
        }
    }
}